package com.siyoumi.app.modules.mall2.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyoumi.app.entity.M2Group;
import com.siyoumi.app.entity.M2Spu;
import com.siyoumi.app.modules.mall2.service.SvcM2Group;
import com.siyoumi.app.modules.mall2.service.SvcM2Spu;
import com.siyoumi.app.modules.mall2.vo.VaM2Spu;
import com.siyoumi.app.service.M2GroupService;
import com.siyoumi.app.service.M2SpuService;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.component.XBean;
import com.siyoumi.util.XReturn;
import com.siyoumi.validator.XValidator;
import com.siyoumi.component.http.InputData;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/xadmin/mall2/m2__spu__sku__edit")
public class m2__spu__sku__edit
        extends AdminApiController {
    @GetMapping()
    public XReturn index() {
        setPageTitle("商品-编辑");

        SvcM2Spu app = SvcM2Spu.getBean();

        Map<String, Object> data = new HashMap<>();
        if (isAdminEdit()) {
            M2Spu entity = SvcM2Spu.getApp().loadEntity(getID());

            HashMap<String, Object> dataAppend = new LinkedHashMap<>();
            dataAppend.put("id", entity.getKey());
            //
            //合并
            data = entity.toMap();
            data.putAll(dataAppend);
        }
        getR().setData("data", data);

        //分组
        QueryWrapper<M2Group> queryGroup = SvcM2Group.getBean().listQuery(InputData.getIns());
        queryGroup.select("mgroup_id", "mgroup_name");
        List<M2Group> listGroup = SvcM2Group.getApp().list(queryGroup);
        setPageInfo("list_group", listGroup);

        return getR();
    }


    @Transactional
    @PostMapping("/save")
    public XReturn save(@Validated() VaM2Spu vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result);
        //自定交验证
        M2Group entityGroup = M2GroupService.getBean().getEntity(vo.getMspu_group_id());
        if (entityGroup == null) {
            result.addError(XValidator.getErr("mspu_group_id", "分组ID异常"));
        }

        M2SpuService app = M2SpuService.getBean();

        List<String> ignoreField = new ArrayList<>();
        if (isAdminEdit()) {
            ignoreField.add("mspu_x_id");
            ignoreField.add("mspu_type");
            ignoreField.add("mspu_app_id");
        }

        InputData inputData = InputData.fromRequest();
        inputData.putAll(XBean.toMap(vo));
        return app.saveEntity(inputData, true, ignoreField);
    }
}
